package co.za.itweb.itwebafrica;


import java.io.File;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;


@SuppressLint("SetJavaScriptEnabled")
public class Splash2 extends Activity {
	
	

	int max;
	
	ProgressDialog progressDialog;

	private int width;

	private String mainfolder;

	private String density;

	private int bannerHolderWidth;

	private WebView banner;
	
	ProgressBar b;
	ProgressDialog progDialog;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash2);
		
		getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);

		/*
		 int colors[] =  {Color.parseColor("#FF4a79bc"),Color.parseColor("#FF4a79bc")};
		GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,
				colors);
		this.getWindow().setBackgroundDrawable(grad);
		*/
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay()
				.getMetrics(metrics);

		 width = (int) metrics.widthPixels;

		
		    		
		
		 
		
		 
		 

			if(determineDensity()=="ldpi"){
				bannerHolderWidth=(int) (width*1.3);
			}else if(determineDensity()=="mdpi"){
				bannerHolderWidth=(int) (width);
			}else if(determineDensity()=="hdpi"){
				bannerHolderWidth=(int) (width)-(width/3);
			}else if(determineDensity()=="xdpi"){
				bannerHolderWidth=(int) (width)-(width/2);
			}
			
			if(bannerHolderWidth > 728){
				bannerHolderWidth=728;
			}
			
			if(width <= 250){
				 mainfolder="240";
				
			
			 }else if(width >250 && width <= 320){
				 mainfolder="320";
				
			 }else if(width>320 && width <= 480){
				 mainfolder="480";
				 
			 }else if(width>480 && width <= 720){
				 mainfolder="720";
			 }else if(width>720 && width <= 800){
				 mainfolder="800";
			 }else if(width>800 && width <= 1280){
				 mainfolder="1280";
			 }else{
				 mainfolder="1280";
			 }
			
			
			
			
			
						RelativeLayout linLayout = (RelativeLayout) findViewById(R.id.banner);
						/*
						if(bannerHolderWidth >= 728 && width>768){	
		    RelativeLayout.LayoutParams layoutParams= new RelativeLayout.LayoutParams(bannerHolderWidth, RelativeLayout.LayoutParams.WRAP_CONTENT);
		    layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 1);
		    banner = new WebView(this); 
			linLayout.addView(banner, layoutParams);
		}else{
			RelativeLayout.LayoutParams layoutParams= new RelativeLayout.LayoutParams(width, RelativeLayout.LayoutParams.WRAP_CONTENT);
			layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 1);
			banner = new WebView(this); 
			linLayout.addView(banner, layoutParams);
		}
						
			*/			
						
			 RelativeLayout.LayoutParams layoutParams= new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
		    // layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 1);
			 banner = new WebView(this); 
			 linLayout.addView(banner, layoutParams);
		
		 progDialog = new ProgressDialog(this);
        progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progDialog.setMessage("Loading sponsor...");
        progDialog.setCancelable(true);
        progDialog.setMax(100);
        progDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
	          public void onCancel(DialogInterface dialog) {
	             
	        	  Intent returnIntent = new Intent();
	    			
	            	setResult(RESULT_OK, returnIntent);
	    			returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	    			finish();
	          }
	    });
        progDialog.show();
			 banner.getSettings().setJavaScriptEnabled(true);
             banner.setBackgroundColor(0);
			 banner.setWebViewClient(new myWebClient()); 
		
			 //banner.loadData("<html><head><meta name=\"viewport\" content=\"initial-scale=1.0, user-scalable=no\" /></head><body style=\"margin:0 auto;padding:0px;\"><iframe style=\"width:"+bannerHolderWidth+"px;height:"+bannerHolderWidth+"px;border:0px;margin:0 auto;background-color: rgba(74,121,188,1);\" src=\"http://itweb.mobi/feed/defenceweb/banners/"+mainfolder+"/"+determineDensity()+"/dw.html\"></iframe></body></html>","text/html",null);
			File userfile=new File(Environment.getExternalStorageDirectory()+"/co.za.itweb.itwebafrica/africa.html");
			if(userfile.exists()){
			 banner.loadUrl("file://"+Environment.getExternalStorageDirectory()+"/co.za.itweb.itwebafrica/africa.html");
			}else{
				banner.loadData("<html><head><meta name=\"viewport\" content=\"initial-scale=1.0, user-scalable=no\" /></head><body style=\"margin:0 auto;padding:0px;\"><iframe style=\"width:"+bannerHolderWidth+"px;height:"+bannerHolderWidth+"px;border:0px;margin:0 auto;\" src=\"http://itweb.mobi/feed/itwebafrica/banners/"+mainfolder+"/"+determineDensity()+"/africa.html\"></iframe></body></html>","text/html",null);
			}
		if (internetConnection()) {

				
		} else {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("There is no internet connection.Please connect to the internet and try again.")
			       .setCancelable(false)
			       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	
			        	  dialog.cancel();
			   	    	finish();
			           }
			       
			       
			       });
			AlertDialog alert = builder.create();
			alert.show();
			
		}
	
	}

	public class myWebClient extends WebViewClient  
    {  
		
        @Override  
        public void onPageStarted(WebView view, String url, Bitmap favicon) {  
        
            super.onPageStarted(view, url, favicon);  
        }  
          
        @Override  
        public boolean shouldOverrideUrlLoading(WebView view, String url) {  
           
              
        	getApplicationContext().startActivity(
		                new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
		            return true;
        
              
        }  
          
        @Override  
        public void onPageFinished(WebView view, String url) {  
           
            super.onPageFinished(view, url);  
              
            
            progDialog.dismiss();
            Thread timer= new Thread()
		    {
		        public void run()
		        {
		            try
		            {
		               
		                sleep(4000);
		            }
		            catch (InterruptedException e) 
		            {
		               
		                e.printStackTrace();
		            }
		            finally
		            {   
		                
		            	Intent returnIntent = new Intent();
		    			
		            	setResult(RESULT_OK, returnIntent);
		    			returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		    			finish();
		            }
		        }
		    };
		    timer.start();
        }  
    }  
      
  
	public boolean internetConnection() {
		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getActiveNetworkInfo();

		return (info != null && info.isConnected());

	}

	
	
	public String determineDensity(){
		switch (getResources().getDisplayMetrics().densityDpi) {
		case DisplayMetrics.DENSITY_LOW:
			density="ldpi";
			
		    break;
		case DisplayMetrics.DENSITY_MEDIUM:
			density= "mdpi";
			
			 break;
		case DisplayMetrics.DENSITY_HIGH:
			density= "hdpi";
			
			 break;
		case DisplayMetrics.DENSITY_XHIGH:
			density= "xdpi";
			
			 break;
		}
		return density;
	}

	

	

	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
	  
	    if ((keyCode == KeyEvent.KEYCODE_BACK)){
	    	if(progDialog.isShowing()){
	    		progDialog.dismiss();
	    	}
	    	Intent returnIntent = new Intent();
	    	setResult(RESULT_OK, returnIntent);
			returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			finish();
	    	
	    	
	    }
	    
	  
	    return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onBackPressed() {
		if(progDialog.isShowing()){
    		progDialog.dismiss();
    	}
		Intent returnIntent = new Intent();
		setResult(RESULT_OK, returnIntent);
		returnIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		finish();
    	
    	finish();
	return;
	}
	
	
	


}
